package club.bigtian.statusbar;

import cn.hutool.json.JSONUtil;
import com.google.gson.Gson;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.ui.jcef.JBCefBrowser;
import com.intellij.ui.jcef.JBCefBrowserBase;
import com.intellij.ui.jcef.JBCefClient;
import com.intellij.ui.jcef.JBCefJSQuery;
import org.cef.browser.CefBrowser;
import org.cef.browser.CefFrame;
import org.cef.handler.CefLoadHandlerAdapter;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 使用JCEF嵌入网页的卡片对话框
 */
public class WebCardDialog extends DialogWrapper {
    
    private final Project project;
    private JBCefBrowser browser;
    private JBCefJSQuery jsQuery;

    public WebCardDialog(@Nullable Project project) {
        super(project);
        this.project = project;
        setTitle("账户信息");
        setModal(false); // 设置为非模态对话框，允许状态栏继续更新
        init();
    }
    
    @Nullable
    @Override
    protected JComponent createCenterPanel() {
        // 启用JCEF右键上下文菜单（包含View Page Source、Inspect等选项）
        enableContextMenu();

        // 创建JCEF浏览器
        browser = new JBCefBrowser();

        // 创建JavaScript桥接
        setupJavaScriptBridge();

        // 加载HTML内容
        loadHtmlContent();

        // 创建主面板
        JPanel panel = new JPanel(new BorderLayout());
        panel.add(browser.getComponent(), BorderLayout.CENTER);
        panel.setPreferredSize(new Dimension(850, 550));

        return panel;
    }

    /**
     * 启用JCEF右键上下文菜单
     */
    private void enableContextMenu() {
        try {
            // 启用DevTools上下文菜单
            Registry.get("ide.browser.jcef.contextMenu.devTools.enabled").setValue(true);
            System.out.println("✅ JCEF右键上下文菜单已启用");
        } catch (Exception e) {
            System.err.println("⚠️ 无法启用JCEF上下文菜单: " + e.getMessage());
        }
    }
    
    /**
     * 设置JavaScript桥接
     */
    private void setupJavaScriptBridge() {
        jsQuery = JBCefJSQuery.create((JBCefBrowserBase) browser);

        // 处理来自JavaScript的调用
        jsQuery.addHandler((data) -> {
            // 解析数据格式: "action:data:param"
            // 只分割第一个冒号获取action
            int firstColon = data.indexOf(':');
            if (firstColon > 0) {
                String action = data.substring(0, firstColon);
                String remaining = data.substring(firstColon + 1);

                // 移除末尾的冒号（如果有）
                if (remaining.endsWith(":")) {
                    remaining = remaining.substring(0, remaining.length() - 1);
                }

                // 在UI线程中处理操作
                String finalData = remaining;
                SwingUtilities.invokeLater(() -> handleAction(action, finalData, ""));
            } else {
                // 处理没有数据的action（如refreshAll）
                SwingUtilities.invokeLater(() -> handleAction(data, "", ""));
            }
            return null;
        });
    }

    /**
     * 处理来自网页的操作
     */
    private void handleAction(String action, String dataStr, String param) {
        System.out.println("收到操作: " + action + ", 数据: " + dataStr);

        // 使用Gson解析JSON数据（更可靠）
        TokenConfig.TokenRawData tokenData = null;
        try {
            // 使用Gson解析JSON字符串
            Gson gson = new Gson();
            tokenData = gson.fromJson(dataStr, TokenConfig.TokenRawData.class);

            // 如果转换成功，输出详细信息
            if (tokenData != null && tokenData.getTenantUrl() != null) {
                System.out.println("✅ 成功解析Token数据:");
                System.out.println("   租户URL: " + tokenData.getTenantUrl());
                System.out.println("   邮箱: " + tokenData.getEmailNote());
                System.out.println("   状态: " + tokenData.getBanStatus());
                if (tokenData.getPortalInfo() != null) {
                    System.out.println("   余额: " + tokenData.getPortalInfo().getCreditsBalance());
                    System.out.println("   过期时间: " + tokenData.getPortalInfo().getExpiryDate());
                }
            } else {
                // 转换失败，说明不是有效的JSON
                tokenData = null;
                System.out.println("⚠️ 数据不是有效的JSON格式");
            }
        } catch (Exception e) {
            // 解析失败，说明不是JSON格式
            tokenData = null;
            System.out.println("⚠️ 数据不是JSON格式: " + e.getMessage());
            e.printStackTrace();
        }

        switch (action) {
            case "open":
                handleOpen(tokenData);
                break;
            case "refresh":
                handleRefresh(tokenData);
                break;
            case "refreshAll":
                handleRefreshAll();
                break;
            case "delete":
                handleDelete(tokenData);
                break;
            case "saveSettings":
                handleSaveSettings(dataStr);
                break;
            case "loadSettings":
                handleLoadSettings();
                break;
            default:
                System.out.println("未知操作: " + action);
        }
    }

    /**
     * 打开账户 - 使用选中的token凭证
     */
    private void handleOpen(TokenConfig.TokenRawData tokenData) {
        if (tokenData != null) {
            String domain = extractDomain(tokenData.getTenantUrl());
            System.out.println("========================================");
            System.out.println("🔓 使用账户: " + domain);
            System.out.println("  邮箱: " + tokenData.getEmailNote());
            if (tokenData.getPortalInfo() != null) {
                System.out.println("  余额: " + tokenData.getPortalInfo().getCreditsBalance());
            }
            System.out.println("  状态: " + tokenData.getBanStatus());
            System.out.println("========================================");

            // 获取原始token数据
            String tenantUrl = tokenData.getTenantUrl();
            String authSession = tokenData.getAccessToken();

            if (tenantUrl != null && authSession != null && !tenantUrl.isEmpty() && !authSession.isEmpty()) {
                // 使用反射保存凭证到Augment插件
                try {
                    CredentialManager credentialManager = new CredentialManager();
                    credentialManager.reflectionSaveCredentials(tenantUrl, authSession);

                    System.out.println("✅ 凭证已更新到Augment插件");
                    System.out.println("   Tenant URL: " + tenantUrl);
                    System.out.println("   Auth Session: " + authSession.substring(0, Math.min(50, authSession.length())) + "...");

                    // 记录当前使用的账户信息
                    TokenConfig.setCurrentAccount(tokenData);

                    // 更新状态栏余额显示
                    updateStatusBarBalance(tokenData);

                    // 显示成功通知
                    NotificationUtil.showAccountSwitchSuccess(project, domain, tokenData.getEmailNote());
                } catch (Exception e) {
                    System.err.println("❌ 更新凭证失败: " + e.getMessage());
                    e.printStackTrace();

                    // 根据异常类型显示不同的错误信息
                    String errorMsg = e.getMessage();
                    if (errorMsg != null && errorMsg.contains("Augment Plugin Not Found")) {
                        NotificationUtil.showAugmentPluginNotFound(project);
                    } else {
                        NotificationUtil.showAccountSwitchError(project, domain,
                            errorMsg != null ? errorMsg : "未知错误");
                    }
                }
            } else {
                System.err.println("⚠️ Token数据不完整，无法更新凭证");
                System.err.println("   Tenant URL: " + (tenantUrl != null ? tenantUrl : "null"));

                NotificationUtil.showTokenDataIncomplete(project);
            }
        } else {
            System.out.println("⚠️ 打开账户: 数据为空");
            NotificationUtil.showError(project, "操作失败", "账户数据为空");
        }
    }

    /**
     * 从URL提取域名
     */
    private String extractDomain(String url) {
        if (url == null || url.isEmpty()) {
            return "未知域名";
        }
        try {
            // 移除协议部分
            String domain = url.replaceAll("^https?://", "");
            // 移除路径部分
            domain = domain.split("/")[0];
            return domain;
        } catch (Exception e) {
            return url;
        }
    }

    /**
     * 刷新单个账户
     */
    private void handleRefresh(TokenConfig.TokenRawData tokenData) {
        if (tokenData != null) {
            String domain = extractDomain(tokenData.getTenantUrl());
            System.out.println("🔄 刷新单个账户: " + domain);

            // 在后台线程执行刷新
            new Thread(() -> {
                try {
                    List<TokenConfig.TokenRawData> singleToken = new ArrayList<>();
                    singleToken.add(tokenData);

                    List<TokenRefreshService.RefreshResult> results =
                        TokenRefreshService.batchRefreshAccounts(singleToken);

                    if (!results.isEmpty() && results.get(0).isSuccess()) {
                        // 更新配置文件中的数据
                        updateTokenInConfig(results.get(0));

                        // 重新加载页面数据
                        SwingUtilities.invokeLater(() -> {
                            reloadCardData();
                            NotificationUtil.showSuccess(project, "刷新成功",
                                "账户 " + domain + " 已刷新");
                        });
                    } else {
                        SwingUtilities.invokeLater(() -> {
                            NotificationUtil.showWarning(project, "刷新失败",
                                "账户 " + domain + " 刷新失败");
                        });
                    }
                } catch (Exception e) {
                    System.err.println("❌ 刷新失败: " + e.getMessage());
                    e.printStackTrace();
                    SwingUtilities.invokeLater(() -> {
                        NotificationUtil.showError(project, "刷新失败", e.getMessage());
                    });
                }
            }).start();
        } else {
            System.out.println("刷新账户: 数据为空");
        }
    }

    /**
     * 刷新所有账户
     */
    private void handleRefreshAll() {
        System.out.println("🔄 开始刷新所有账户...");

        // 显示刷新中的通知
        NotificationUtil.showInfo(project, "正在刷新", "正在并发刷新所有账户，请稍候...");

        // 在后台线程执行刷新
        new Thread(() -> {
            try {
                // 加载所有token
                List<TokenConfig.TokenRawData> tokens = TokenConfig.tryLoadTokens();

                if (tokens == null || tokens.isEmpty()) {
                    SwingUtilities.invokeLater(() -> {
                        NotificationUtil.showWarning(project, "无数据", "没有找到需要刷新的账户");
                    });
                    return;
                }

                // 并发刷新所有账户
                List<TokenRefreshService.RefreshResult> results =
                    TokenRefreshService.batchRefreshAccounts(tokens);

                // 更新配置文件
                for (TokenRefreshService.RefreshResult result : results) {
                    if (result.isSuccess()) {
                        updateTokenInConfig(result);
                    }
                }

                // 统计结果
                long successCount = results.stream().filter(TokenRefreshService.RefreshResult::isSuccess).count();
                long failCount = results.size() - successCount;

                // 重新加载页面数据
                SwingUtilities.invokeLater(() -> {
                    reloadCardData();
                    NotificationUtil.showSuccess(project, "刷新完成",
                        String.format("成功: %d, 失败: %d", successCount, failCount));
                });

            } catch (Exception e) {
                System.err.println("❌ 批量刷新失败: " + e.getMessage());
                e.printStackTrace();
                SwingUtilities.invokeLater(() -> {
                    NotificationUtil.showError(project, "刷新失败", e.getMessage());
                });
            }
        }).start();
    }

    /**
     * 更新配置文件中的token数据
     */
    private void updateTokenInConfig(TokenRefreshService.RefreshResult result) {
        try {
            List<TokenConfig.TokenRawData> tokens = TokenConfig.tryLoadTokens();

            for (TokenConfig.TokenRawData token : tokens) {
                if (token.getId().equals(result.getId())) {
                    // 只有成功获取到明确状态时才更新 ban_status（避免网络错误导致误判）
                    if (result.getBanStatus() != null && !result.getBanStatus().startsWith("ERROR")) {
                        token.setBanStatus(result.getBanStatus());
                        System.out.println("  📝 更新状态: " + result.getEmailNote() + " -> " + result.getBanStatus());
                    } else {
                        System.out.println("  ⚠️ 跳过状态更新: " + result.getEmailNote() + " (状态检查失败，保留原状态)");
                    }

                    // 更新Portal信息
                    if (result.getPortalInfo() != null) {
                        TokenConfig.PortalInfo portalInfo = new TokenConfig.PortalInfo();
                        portalInfo.setCreditsBalance(result.getPortalInfo().getCreditsBalance());
                        portalInfo.setExpiryDate(result.getPortalInfo().getExpiryDate());
                        token.setPortalInfo(portalInfo);
                    }

                    // 更新时间
                    token.setUpdatedAt(java.time.Instant.now().toString());
                    break;
                }
            }

            // 保存回配置文件
            TokenConfig.saveTokens(tokens);

        } catch (Exception e) {
            System.err.println("❌ 更新配置文件失败: " + e.getMessage());
        }
    }

    /**
     * 重新加载卡片数据
     */
    private void reloadCardData() {
        System.out.println("🔄 reloadCardData() 被调用");

        // 重新从文件加载数据
        String cardDataJson = buildCardDataJson();
        System.out.println("📦 构建的JSON数据长度: " + (cardDataJson != null ? cardDataJson.length() : 0));

        // 转义JSON字符串
        String escapedJson = escapeJavaScript(cardDataJson);
        String script = "if (typeof loadCards === 'function') { " +
                       "console.log('🔄 调用loadCards刷新数据'); " +
                       "loadCards('" + escapedJson + "'); " +
                       "} else { " +
                       "console.error('❌ loadCards函数不存在'); " +
                       "}";

        System.out.println("📝 执行JavaScript脚本刷新页面");
        browser.getCefBrowser().executeJavaScript(script, browser.getCefBrowser().getURL(), 0);
    }

    /**
     * 转义JavaScript字符串
     */
    private String escapeJavaScript(String str) {
        if (str == null) return "";
        return str.replace("\\", "\\\\")
                  .replace("'", "\\'")
                  .replace("\"", "\\\"")
                  .replace("\n", "\\n")
                  .replace("\r", "\\r");
    }

    /**
     * 删除账户（已在前端确认）
     */
    private void handleDelete(TokenConfig.TokenRawData tokenData) {
        if (tokenData == null) {
            System.out.println("⚠️ 删除失败：账户数据为空");
            NotificationUtil.showError(project, "删除失败", "账户数据为空");
            return;
        }

        String domain = extractDomain(tokenData.getTenantUrl());
        String emailNote = tokenData.getEmailNote();
        String deleteId = tokenData.getId();

        System.out.println("🗑️ 开始删除账户:");
        System.out.println("   域名: " + domain);
        System.out.println("   邮箱: " + emailNote);
        System.out.println("   ID: " + deleteId);

        // 检查ID是否为空
        if (deleteId == null || deleteId.trim().isEmpty()) {
            System.out.println("⚠️ 删除失败：账户ID为空");
            NotificationUtil.showError(project, "删除失败", "账户ID为空，无法删除");
            return;
        }

        try {
            // 从tokens.json中删除
            List<TokenConfig.TokenRawData> tokens = TokenConfig.tryLoadTokens();

            if (tokens == null || tokens.isEmpty()) {
                System.out.println("⚠️ 配置文件中没有账户数据");
                NotificationUtil.showWarning(project, "删除失败", "配置文件中没有账户数据");
                return;
            }

            System.out.println("📋 当前配置文件中有 " + tokens.size() + " 个账户");

            // 打印所有账户的ID用于调试
            for (int i = 0; i < tokens.size(); i++) {
                TokenConfig.TokenRawData token = tokens.get(i);
                String tokenId = token.getId();
                boolean match = tokenId != null && tokenId.equals(deleteId);
                System.out.println("   [" + i + "] ID: " + tokenId +
                                 ", 邮箱: " + token.getEmailNote() +
                                 ", 匹配: " + (match ? "✅" : "❌"));
            }

            boolean removed = tokens.removeIf(token -> {
                if (token.getId() == null) {
                    System.out.println("⚠️ 发现ID为null的账户: " + token.getEmailNote());
                    return false;
                }
                boolean match = token.getId().equals(deleteId);
                if (match) {
                    System.out.println("🎯 找到匹配的账户，准备删除: " + token.getEmailNote());
                }
                return match;
            });

            if (removed) {
                System.out.println("✅ 从列表中移除成功，剩余 " + tokens.size() + " 个账户");

                // 保存更新后的tokens
                TokenConfig.saveTokens(tokens);
                System.out.println("💾 已保存到配置文件");

                // 显示成功通知
                NotificationUtil.showSuccess(project, "删除成功", "账户 " + emailNote + " 已删除");

                // 重新加载页面数据 - 确保在EDT线程中执行
                System.out.println("🔄 开始重新加载页面数据...");
                javax.swing.SwingUtilities.invokeLater(() -> {
                    reloadCardData();
                    System.out.println("✅ 页面数据重新加载完成");
                });
            } else {
                System.out.println("⚠️ 未找到要删除的账户 (ID不匹配)");
                NotificationUtil.showWarning(project, "删除失败", "未找到该账户，可能已被删除");
            }
        } catch (Exception e) {
            System.err.println("❌ 删除账户失败: " + e.getMessage());
            e.printStackTrace();
            NotificationUtil.showError(project, "删除失败", e.getMessage());
        }
    }

    /**
     * 复制邮箱
     */
    private void handleCopyEmail(String email) {
        System.out.println("复制邮箱: " + email);
        // 复制到剪贴板
        try {
            Toolkit.getDefaultToolkit()
                .getSystemClipboard()
                .setContents(new StringSelection(email), null);
            System.out.println("✅ 邮箱已复制到剪贴板: " + email);
        } catch (Exception e) {
            System.err.println("❌ 复制失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 保存设置
     */
    private void handleSaveSettings(String settingsJson) {
        try {
            System.out.println("💾 保存设置: " + settingsJson);

            // 解析设置JSON
            Gson gson = new Gson();
            TokenConfig.Settings settings = gson.fromJson(settingsJson, TokenConfig.Settings.class);

            if (settings == null || settings.getCountdownSeconds() == null || settings.getCountdownSeconds() <= 0) {
                System.out.println("⚠️ 无效的设置数据");
                NotificationUtil.showError(project, "保存失败", "无效的设置数据");
                return;
            }

            // 保存到配置文件
            TokenConfig.saveSettings(settings);

            // 通知状态栏组件更新倒计时
            updateStatusBarCountdown(settings.getCountdownSeconds());

            // 使用更轻量的通知方式，避免干扰用户
            System.out.println("✅ 设置保存成功: 倒计时=" + settings.getCountdownSeconds() + "秒");

            // 延迟显示通知，避免与模态框关闭动画冲突
            javax.swing.SwingUtilities.invokeLater(() -> {
                NotificationUtil.showSuccess(project, "设置已保存",
                    "倒计时已设置为 " + settings.getCountdownSeconds() + " 秒");
            });

        } catch (Exception e) {
            System.err.println("❌ 保存设置失败: " + e.getMessage());
            e.printStackTrace();
            NotificationUtil.showError(project, "保存失败", e.getMessage());
        }
    }

    /**
     * 加载设置
     */
    private void handleLoadSettings() {
        try {
            System.out.println("📖 加载设置");

            // 从配置文件加载
            TokenConfig.Settings settings = TokenConfig.loadSettings();

            // 转换为JSON并返回给前端
            Gson gson = new Gson();
            String settingsJson = gson.toJson(settings);

            String script = "if (typeof onSettingsLoaded === 'function') { " +
                          "onSettingsLoaded(" + settingsJson + "); " +
                          "} else { " +
                          "console.error('❌ onSettingsLoaded函数不存在'); " +
                          "}";

            browser.getCefBrowser().executeJavaScript(script, browser.getCefBrowser().getURL(), 0);
            System.out.println("✅ 设置已发送到前端");

        } catch (Exception e) {
            System.err.println("❌ 加载设置失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 更新状态栏倒计时
     */
    private void updateStatusBarCountdown(int countdownSeconds) {
        try {
            // 获取状态栏组件并更新倒计时
            com.intellij.openapi.wm.StatusBar statusBar =
                com.intellij.openapi.wm.WindowManager.getInstance().getStatusBar(project);

            if (statusBar != null) {
                com.intellij.openapi.wm.StatusBarWidget widget =
                    statusBar.getWidget("StatusBarTextWidget");

                if (widget instanceof StatusBarTextWidget) {
                    ((StatusBarTextWidget) widget).updateCountdownSettings(countdownSeconds);
                    System.out.println("✅ 状态栏倒计时已更新");
                }
            }
        } catch (Exception e) {
            System.err.println("⚠️ 更新状态栏倒计时失败: " + e.getMessage());
        }
    }

    /**
     * 加载HTML内容
     */
    private void loadHtmlContent() {
        try {
            // 从资源文件读取HTML
            InputStream is = getClass().getResourceAsStream("/html/cards.html");
            if (is != null) {
                String html = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))
                    .lines()
                    .collect(Collectors.joining("\n"));
                
                // 加载HTML
                browser.loadHTML(html);
                
                // 等待页面加载完成后注入数据和桥接函数
                browser.getJBCefClient().addLoadHandler(new CefLoadHandlerAdapter() {
                    @Override
                    public void onLoadEnd(CefBrowser browser, CefFrame frame, int httpStatusCode) {
                        if (frame.isMain()) {
                            // 注入JavaScript桥接函数
                            injectJavaScriptBridge();
                            // 页面加载完成，注入数据
                            injectCardData();
                        }
                    }
                }, browser.getCefBrowser());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 注入JavaScript桥接函数
     */
    private void injectJavaScriptBridge() {
        String script =
            "window.javaCall = function(action, domain, param) {" +
            "    " + jsQuery.inject("action + ':' + domain + ':' + (param || '')") +
            "};";
        browser.getCefBrowser().executeJavaScript(script, browser.getCefBrowser().getURL(), 0);
    }

    /**
     * 注入卡片数据到网页
     */
    private void injectCardData() {
        // 构建JSON数据
        String jsonData = buildCardDataJson();
        
        // 执行JavaScript，将数据传递给网页
        String script = "loadCards('" + jsonData + "');";
        browser.getCefBrowser().executeJavaScript(script, browser.getCefBrowser().getURL(), 0);
    }
    
    /**
     * 构建卡片数据JSON - 使用hutool直接转换
     */
    private String buildCardDataJson() {
        // 从配置文件加载token数据
        List<TokenConfig.TokenRawData> tokens = TokenConfig.tryLoadTokens();

        // 检查是否为空
        if (tokens == null || tokens.isEmpty()) {
            System.out.println("⚠️ 没有找到任何token数据");
            // 显示通知提醒用户
            NotificationUtil.showWarning(project, "未找到Token数据",
                "请先在Tauri应用中添加token数据\n配置文件路径: " + getConfigPathForDisplay());
        }

        // 使用hutool直接转换为JSON字符串
        return JSONUtil.toJsonStr(tokens);
    }

    /**
     * 获取配置文件路径（用于显示）
     */
    private String getConfigPathForDisplay() {
        String os = System.getProperty("os.name").toLowerCase();
        String userHome = System.getProperty("user.home");

        if (os.contains("mac")) {
            return userHome + "/Library/Application Support/com.cubezhao.atm/tokens.json";
        } else if (os.contains("linux")) {
            return userHome + "/.local/share/atm/tokens.json";
        } else if (os.contains("win")) {
            String appData = System.getenv("APPDATA");
            if (appData != null) {
                return appData + "\\com.cubezhao.atm\\tokens.json";
            } else {
                return userHome + "\\AppData\\Roaming\\com.cubezhao.atm\\tokens.json";
            }
        } else {
            return userHome + "/.atm/tokens.json";
        }
    }

    /**
     * 更新状态栏余额显示
     */
    private void updateStatusBarBalance(TokenConfig.TokenRawData tokenData) {
        try {
            if (project == null) {
                System.out.println("⚠️ Project为null，无法更新状态栏");
                return;
            }

            // 获取StatusBar
            com.intellij.openapi.wm.StatusBar statusBar =
                com.intellij.openapi.wm.WindowManager.getInstance().getStatusBar(project);

            if (statusBar == null) {
                System.out.println("⚠️ StatusBar为null，无法更新状态栏");
                return;
            }

            // 获取StatusBarTextWidget
            com.intellij.openapi.wm.StatusBarWidget widget =
                statusBar.getWidget("StatusBarTextWidget");

            if (widget instanceof StatusBarTextWidget) {
                StatusBarTextWidget textWidget = (StatusBarTextWidget) widget;

                // 获取余额
                int balance = 0;
                if (tokenData.getPortalInfo() != null &&
                    tokenData.getPortalInfo().getCreditsBalance() != null) {
                    balance = tokenData.getPortalInfo().getCreditsBalance();
                }

                // 获取封禁状态
                String banStatus = tokenData.getBanStatus();

                // 更新余额显示（带封禁状态）
                textWidget.updateBalanceDisplay(tokenData.getId(), balance, banStatus);
                System.out.println("✅ 状态栏已更新: 余额=" + balance + ", 状态=" + banStatus);
            } else {
                System.out.println("⚠️ 未找到StatusBarTextWidget");
            }
        } catch (Exception e) {
            System.err.println("❌ 更新状态栏余额失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    @Override
    protected Action[] createActions() {
        return new Action[]{getOKAction()};
    }

    @Override
    public void dispose() {
        if (jsQuery != null) {
            jsQuery.dispose();
        }
        if (browser != null) {
            browser.dispose();
        }
        super.dispose();
    }
}

